<template>
  <div class="search-suggestion">
    <van-cell
      title=""
      icon="search"
      v-for="(text, i) in suggestionsList"
      :key="i"
      @click="jumpResult(text)"
    >
      <span slot="title" v-html="htmlLight(text)"></span>
    </van-cell>
  </div>
</template>

<script>
// 导入 获取 联想 建议的 api 接口
import { getSearchSuggestions } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'searchSuggestion',
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      // 需要 替换的 高亮的 html 标签
      htmlStr: '<span style="color:red"></span>',
      suggestionsList: []
    }
  },
  created() {},
  methods: {
    async loadSearchSuggestions(q) {
      const { data } = await getSearchSuggestions(q)
      // console.log(data)
      this.suggestionsList = data.data.options[0] ? data.data.options : []
    },
    htmlLight(text) {
      const highlightStr = `<span style="color:red">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      // text.replace(/匹配的内容/gi, highlightStr)
      return text.replace(reg, highlightStr)
    },
    // 点击 建议 跳转 到 结果页面
    jumpResult(str) {
      // 修改 搜索 文本
      this.$emit('onSearchKey', str)
    }
  },
  computed: {},
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(function(val) {
        this.loadSearchSuggestions(val)
      }, 1000)
    }
  },
  components: {}
}
</script>

<style lang="less" scoped>
.active {
  color: red !important;
}
</style>
